<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
        }
        
        #game-container {
            position: relative;
        }
        
        canvas {
            border: 2px solid #333;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
        
        .game-info {
            display: flex;
            justify-content: space-between;
            width: 400px;
            margin-bottom: 10px;
        }
        
        .score-box {
            background-color: #333;
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            font-size: 18px;
        }
        
        .controls {
            margin-top: 15px;
            display: flex;
            gap: 10px;
        }
        
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        
        #pause-btn {
            background-color: #f39c12;
        }
        
        #pause-btn:hover {
            background-color: #e67e22;
        }
        
        #restart-btn {
            background-color: #e74c3c;
        }
        
        #restart-btn:hover {
            background-color: #c0392b;
        }
        
        .modal {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 24px;
            z-index: 10;
        }
        
        .modal-content {
            background-color: #333;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            max-width: 80%;
        }
        
        .modal h2 {
            margin-top: 0;
        }
        
        .hidden {
            display: none;
        }
        
        .settings {
            margin-top: 20px;
            width: 400px;
            background-color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }
        
        .setting-group {
            margin-bottom: 15px;
        }
        
        .setting-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        select {
            width: 100%;
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        
        .mobile-controls {
            display: none;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 5px;
            margin-top: 15px;
            width: 200px;
            height: 200px;
        }
        
        .mobile-btn {
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 24px;
            cursor: pointer;
            user-select: none;
        }
        
        .mobile-btn:active {
            background-color: #2980b9;
        }
        
        .up-btn {
            grid-column: 2;
            grid-row: 1;
        }
        
        .left-btn {
            grid-column: 1;
            grid-row: 2;
        }
        
        .right-btn {
            grid-column: 3;
            grid-row: 2;
        }
        
        .down-btn {
            grid-column: 2;
            grid-row: 3;
        }
        
        @media (max-width: 480px) {
            canvas {
                width: 100%;
                height: auto;
            }
            
            .game-info, .settings {
                width: 100%;
            }
            
            .mobile-controls {
                display: grid;
            }
        }
    </style>
</head>
<body>
    <h1>贪吃蛇游戏</h1>
    
    <div id="game-container">
        <div class="game-info">
            <div class="score-box">得分: <span id="current-score">0</span></div>
            <div class="score-box">最高分: <span id="high-score">0</span></div>
        </div>
        
        <canvas id="game-canvas" width="400" height="400"></canvas>
        
        <div id="start-modal" class="modal">
            <div class="modal-content">
                <h2>贪吃蛇游戏</h2>
                <p>使用方向键或WASD移动</p>
                <button id="start-btn">开始游戏</button>
            </div>
        </div>
        
        <div id="pause-modal" class="modal hidden">
            <div class="modal-content">
                <h2>游戏暂停</h2>
                <p>当前得分: <span id="pause-score">0</span></p>
                <button id="resume-btn">继续游戏</button>
            </div>
        </div>
        
        <div id="game-over-modal" class="modal hidden">
            <div class="modal-content">
                <h2>游戏结束</h2>
                <p>最终得分: <span id="final-score">0</span></p>
                <p>最高分: <span id="final-high-score">0</span></p>
                <button id="restart-btn-modal">重新开始</button>
            </div>
        </div>
        
        <div class="mobile-controls">
            <button class="mobile-btn up-btn" id="mobile-up">↑</button>
            <button class="mobile-btn left-btn" id="mobile-left">←</button>
            <button class="mobile-btn right-btn" id="mobile-right">→</button>
            <button class="mobile-btn down-btn" id="mobile-down">↓</button>
        </div>
        
        <div class="controls">
            <button id="pause-btn" disabled>暂停</button>
            <button id="restart-btn" disabled>重新开始</button>
        </div>
    </div>
    
    <div class="settings">
        <h3>游戏设置</h3>
        
        <div class="setting-group">
            <label for="difficulty">难度:</label>
            <select id="difficulty">
                <option value="easy">简单</option>
                <option value="medium" selected>中等</option>
                <option value="hard">困难</option>
            </select>
        </div>
        
        <div class="setting-group">
            <label for="snake-color">蛇颜色:</label>
            <select id="snake-color">
                <option value="#4CAF50">绿色</option>
                <option value="#2196F3">蓝色</option>
                <option value="#FF5722">橙色</option>
                <option value="#9C27B0">紫色</option>
                <option value="#607D8B">灰色</option>
            </select>
        </div>
        
        <div class="setting-group">
            <label for="food-color">食物颜色:</label>
            <select id="food-color">
                <option value="#F44336">红色</option>
                <option value="#FFC107">黄色</option>
                <option value="#00BCD4">青色</option>
                <option value="#8BC34A">浅绿色</option>
                <option value="#E91E63">粉色</option>
            </select>
        </div>
        
        <div class="setting-group">
            <label for="bg-color">背景颜色:</label>
            <select id="bg-color">
                <option value="#FFFFFF">白色</option>
                <option value="#F5F5F5">浅灰色</option>
                <option value="#FFF9C4">浅黄色</option>
                <option value="#E3F2FD">浅蓝色</option>
                <option value="#F1F8E9">浅绿色</option>
            </select>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 游戏常量
            const GRID_SIZE = 20;
            const CELL_SIZE = 20;
            const DEFAULT_SPEED = 150; // 中等难度速度(毫秒)
            
            // 游戏变量
            let snake = [];
            let food = {};
            let direction = 'right';
            let nextDirection = 'right';
            let gameInterval;
            let gameState = 'not started'; // 'not started', 'running', 'paused', 'over'
            let score = 0;
            let highScore = localStorage.getItem('snakeHighScore') || 0;
            
            // 游戏配置
            let config = {
                speed: DEFAULT_SPEED,
                snakeColor: '#4CAF50',
                foodColor: '#F44336',
                bgColor: '#FFFFFF'
            };
            
            // DOM元素
            const canvas = document.getElementById('game-canvas');
            const ctx = canvas.getContext('2d');
            const currentScoreEl = document.getElementById('current-score');
            const highScoreEl = document.getElementById('high-score');
            const pauseScoreEl = document.getElementById('pause-score');
            const finalScoreEl = document.getElementById('final-score');
            const finalHighScoreEl = document.getElementById('final-high-score');
            
            const startModal = document.getElementById('start-modal');
            const pauseModal = document.getElementById('pause-modal');
            const gameOverModal = document.getElementById('game-over-modal');
            
            const startBtn = document.getElementById('start-btn');
            const pauseBtn = document.getElementById('pause-btn');
            const resumeBtn = document.getElementById('resume-btn');
            const restartBtn = document.getElementById('restart-btn');
            const restartBtnModal = document.getElementById('restart-btn-modal');
            
            // 移动控制按钮
            const mobileUpBtn = document.getElementById('mobile-up');
            const mobileLeftBtn = document.getElementById('mobile-left');
            const mobileRightBtn = document.getElementById('mobile-right');
            const mobileDownBtn = document.getElementById('mobile-down');
            
            // 设置下拉菜单
            const difficultySelect = document.getElementById('difficulty');
            const snakeColorSelect = document.getElementById('snake-color');
            const foodColorSelect = document.getElementById('food-color');
            const bgColorSelect = document.getElementById('bg-color');
            
            // 初始化游戏
            initGame();
            
            // 事件监听器
            startBtn.addEventListener('click', startGame);
            pauseBtn.addEventListener('click', pauseGame);
            resumeBtn.addEventListener('click', resumeGame);
            restartBtn.addEventListener('click', restartGame);
            restartBtnModal.addEventListener('click', restartGame);
            
            // 键盘控制
            document.addEventListener('keydown', handleKeyDown);
            
            // 移动控制按钮
            mobileUpBtn.addEventListener('click', () => changeDirection('up'));
            mobileLeftBtn.addEventListener('click', () => changeDirection('left'));
            mobileRightBtn.addEventListener('click', () => changeDirection('right'));
            mobileDownBtn.addEventListener('click', () => changeDirection('down'));
            
            // 触摸控制
            let touchStartX, touchStartY;
            canvas.addEventListener('touchstart', (e) => {
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
            });
            
            canvas.addEventListener('touchend', (e) => {
                const touchEndX = e.changedTouches[0].clientX;
                const touchEndY = e.changedTouches[0].clientY;
                
                const dx = touchEndX - touchStartX;
                const dy = touchEndY - touchStartY;
                
                // 确定滑动的方向
                if (Math.abs(dx) > Math.abs(dy)) {
                    // 水平滑动
                    if (dx > 0 && direction !== 'left') {
                        changeDirection('right');
                    } else if (dx < 0 && direction !== 'right') {
                        changeDirection('left');
                    }
                } else {
                    // 垂直滑动
                    if (dy > 0 && direction !== 'up') {
                        changeDirection('down');
                    } else if (dy < 0 && direction !== 'down') {
                        changeDirection('up');
                    }
                }
            });
            
            // 设置变化监听
            difficultySelect.addEventListener('change', updateDifficulty);
            snakeColorSelect.addEventListener('change', updateSnakeColor);
            foodColorSelect.addEventListener('change', updateFoodColor);
            bgColorSelect.addEventListener('change', updateBgColor);
            
            // 游戏函数
            function initGame() {
                // 初始化蛇
                snake = [
                    {x: 5, y: 10},
                    {x: 4, y: 10},
                    {x: 3, y: 10}
                ];
                
                direction = 'right';
                nextDirection = 'right';
                score = 0;
                currentScoreEl.textContent = '0';
                highScoreEl.textContent = highScore;
                
                // 生成食物
                generateFood();
                
                // 绘制初始状态
                draw();
            }
            
            function startGame() {
                if (gameState === 'not started' || gameState === 'over') {
                    initGame();
                    gameState = 'running';
                    startModal.classList.add('hidden');
                    pauseBtn.disabled = false;
                    restartBtn.disabled = false;
                    
                    // 开始游戏循环
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, config.speed);
                }
            }
            
            function pauseGame() {
                if (gameState === 'running') {
                    gameState = 'paused';
                    clearInterval(gameInterval);
                    pauseScoreEl.textContent = score;
                    pauseModal.classList.remove('hidden');
                }
            }
            
            function resumeGame() {
                if (gameState === 'paused') {
                    gameState = 'running';
                    pauseModal.classList.add('hidden');
                    gameInterval = setInterval(gameLoop, config.speed);
                }
            }
            
            function restartGame() {
                gameState = 'not started';
                clearInterval(gameInterval);
                gameOverModal.classList.add('hidden');
                startModal.classList.remove('hidden');
                pauseBtn.disabled = true;
                restartBtn.disabled = true;
            }
            
            function gameLoop() {
                moveSnake();
                
                if (checkCollision()) {
                    gameOver();
                    return;
                }
                
                checkFood();
                draw();
            }
            
            function moveSnake() {
                // 更新方向
                direction = nextDirection;
                
                // 移动蛇身
                const head = {x: snake[0].x, y: snake[0].y};
                
                switch (direction) {
                    case 'up':
                        head.y--;
                        break;
                    case 'down':
                        head.y++;
                        break;
                    case 'left':
                        head.x--;
                        break;
                    case 'right':
                        head.x++;
                        break;
                }
                
                // 在数组开头添加新的头部
                snake.unshift(head);
                
                // 移除尾部(除非吃到食物)
                if (!checkFood()) {
                    snake.pop();
                }
            }
            
            function checkCollision() {
                const head = snake[0];
                
                // 检查墙壁碰撞
                if (
                    head.x < 0 || 
                    head.x >= GRID_SIZE || 
                    head.y < 0 || 
                    head.y >= GRID_SIZE
                ) {
                    return true;
                }
                
                // 检查自身碰撞(从第二段开始检查，因为是刚刚移动的头部与新位置)
                for (let i = 1; i < snake.length; i++) {
                    if (head.x === snake[i].x && head.y === snake[i].y) {
                        return true;
                    }
                }
                
                return false;
            }
            
            function checkFood() {
                const head = snake[0];
                
                if (head.x === food.x && head.y === food.y) {
                    // 加分
                    score += 10;
                    currentScoreEl.textContent = score;
                    
                    // 更新最高分
                    if (score > highScore) {
                        highScore = score;
                        highScoreEl.textContent = highScore;
                        localStorage.setItem('snakeHighScore', highScore);
                    }
                    
                    // 生成新食物
                    generateFood();
                    return true;
                }
                
                return false;
            }
            
            function generateFood() {
                let newFoodPos;
                let validPosition = false;
                
                while (!validPosition) {
                    newFoodPos = {
                        x: Math.floor(Math.random() * GRID_SIZE),
                        y: Math.floor(Math.random() * GRID_SIZE)
                    };
                    
                    // 检查食物不与蛇体重叠
                    validPosition = true;
                    for (let segment of snake) {
                        if (segment.x === newFoodPos.x && segment.y === newFoodPos.y) {
                            validPosition = false;
                            break;
                        }
                    }
                }
                
                food = newFoodPos;
            }
            
            function gameOver() {
                gameState = 'over';
                clearInterval(gameInterval);
                
                // 更新结束弹窗分数
                finalScoreEl.textContent = score;
                finalHighScoreEl.textContent = highScore;
                
                // 显示结束弹窗
                gameOverModal.classList.remove('hidden');
            }
            
            function draw() {
                // 清空画布
                ctx.fillStyle = config.bgColor;
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                // 绘制食物
                ctx.fillStyle = config.foodColor;
                ctx.beginPath();
                const foodX = food.x * CELL_SIZE + CELL_SIZE / 2;
                const foodY = food.y * CELL_SIZE + CELL_SIZE / 2;
                ctx.arc(foodX, foodY, CELL_SIZE / 2 - 2, 0, Math.PI * 2);
                ctx.fill();
                
                // 绘制蛇
                ctx.fillStyle = config.snakeColor;
                for (let i = 0; i < snake.length; i++) {
                    const segment = snake[i];
                    
                    // 头部圆形，身体方块
                    if (i === 0) {
                        ctx.beginPath();
                        const headX = segment.x * CELL_SIZE + CELL_SIZE / 2;
                        const headY = segment.y * CELL_SIZE + CELL_SIZE / 2;
                        ctx.arc(headX, headY, CELL_SIZE / 2 - 2, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 眼睛
                        ctx.fillStyle = 'white';
                        let eye1X, eye1Y, eye2X, eye2Y;
                        
                        switch (direction) {
                            case 'up':
                                eye1X = headX - 4;
                                eye1Y = headY - 3;
                                eye2X = headX + 4;
                                eye2Y = headY - 3;
                                break;
                            case 'down':
                                eye1X = headX - 4;
                                eye1Y = headY + 3;
                                eye2X = headX + 4;
                                eye2Y = headY + 3;
                                break;
                            case 'left':
                                eye1X = headX - 3;
                                eye1Y = headY - 4;
                                eye2X = headX - 3;
                                eye2Y = headY + 4;
                                break;
                            case 'right':
                                eye1X = headX + 3;
                                eye1Y = headY - 4;
                                eye2X = headX + 3;
                                eye2Y = headY + 4;
                                break;
                        }
                        
                        ctx.beginPath();
                        ctx.arc(eye1X, eye1Y, 2, 0, Math.PI * 2);
                        ctx.fill();
                        
                        ctx.beginPath();
                        ctx.arc(eye2X, eye2Y, 2, 0, Math.PI * 2);
                        ctx.fill();
                        
                        ctx.fillStyle = config.snakeColor;
                    } else {
                        ctx.fillRect(
                            segment.x * CELL_SIZE + 2, 
                            segment.y * CELL_SIZE + 2, 
                            CELL_SIZE - 4, 
                            CELL_SIZE - 4
                        );
                    }
                }
            }
            
            function handleKeyDown(e) {
                if (gameState !== 'running') return;
                
                switch (e.key) {
                    case 'ArrowUp':
                    case 'w':
                    case 'W':
                        if (direction !== 'down') nextDirection = 'up';
                        break;
                    case 'ArrowDown':
                    case 's':
                    case 'S':
                        if (direction !== 'up') nextDirection = 'down';
                        break;
                    case 'ArrowLeft':
                    case 'a':
                    case 'A':
                        if (direction !== 'right') nextDirection = 'left';
                        break;
                    case 'ArrowRight':
                    case 'd':
                    case 'D':
                        if (direction !== 'left') nextDirection = 'right';
                        break;
                    case ' ':
                    case 'Spacebar':
                        pauseGame();
                        break;
                }
            }
            
            function changeDirection(newDirection) {
                if (gameState !== 'running') return;
                
                // 防止180度转向
                if (
                    (direction === 'up' && newDirection === 'down') ||
                    (direction === 'down' && newDirection === 'up') ||
                    (direction === 'left' && newDirection === 'right') ||
                    (direction === 'right' && newDirection === 'left')
                ) {
                    return;
                }
                
                nextDirection = newDirection;
            }
            
            // 设置更新函数
            function updateDifficulty() {
                const difficulty = difficultySelect.value;
                
                switch (difficulty) {
                    case 'easy':
                        config.speed = DEFAULT_SPEED + 50;
                        break;
                    case 'medium':
                        config.speed = DEFAULT_SPEED;
                        break;
                    case 'hard':
                        config.speed = DEFAULT_SPEED - 50;
                        break;
                }
                
                // 如果游戏正在进行中，更新游戏速度
                if (gameState === 'running') {
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, config.speed);
                }
            }
            
            function updateSnakeColor() {
                config.snakeColor = snakeColorSelect.value;
                draw();
            }
            
            function updateFoodColor() {
                config.foodColor = foodColorSelect.value;
                draw();
            }
            
            function updateBgColor() {
                config.bgColor = bgColorSelect.value;
                draw();
            }
            
            // 初始化设置显示
            updateDifficulty();
            updateSnakeColor();
            updateFoodColor();
            updateBgColor();
        });
    </script>
</body>
</html>